<template>
  <div>
    <div id="map-direction" v-loading="loading"></div>
    <div v-show="false">
      <TourMarker v-for="(v,i) in data.spot"
                  :key="i"
                  :ref="`tourMarker${v.spotId}`"
                  :id="`tourMarker${v.spotId}`"
                  :index="i"
                  :spot="v"
                  :spots="data.spot"
      />
    </div>
  </div>
</template>

<script>
const key = 'EPXBZ-WLLKX-HKH4S-Z5MX4-BEEFQ-6NBKB'
import TourMarker from './TourMarker' //自定义游览点标记
import { jsonp } from 'vue-jsonp'

export default {
  components: { TourMarker },
  props: {
    data: {
      type: Object,
      default: {},
      required: true
    },
  },
  data () {
    return {
      loading: true,
      map: null,
      marker: [],
      polyline: [],
      distance: 0,
      routePath: [],
      routePathObj: {},
      groundOverlay: null
    }
  },
  created () {
    window.initMapPreview = function () {
      this.map = new qq.maps.Map('map-direction', {
        ...this.data.center ? { center: new qq.maps.LatLng(...this.data.center) } : {},
        zoom: this.data.zoom || 17
      })

      qq.maps.event.addListener(this.map, 'zoom_changed', e => {
          this.$emit('zoom', this.map.getZoom())
        }
      )

      this.renderImg()
      this.renderMarker()
      this.renderPath(this.data.routePath)

      this.loading = false
    }.bind(this)

    window.cb = function (res, i) {
      if (res.result) {
        this.distance += res.result.routes[0].distance
        let coors = res.result.routes[0].polyline, pl = []
        //坐标解压（返回的点串坐标，通过前向差分进行压缩）
        let kr = 1000000
        for (let i = 2; i < coors.length; i++) {
          coors[i] = Number(coors[i - 2]) + Number(coors[i]) / kr
        }
        //将解压后的坐标放入点串数组pl中
        let temp = []
        for (let i = 0; i < coors.length; i += 2) {
          pl.push(new qq.maps.LatLng(coors[i], coors[i + 1]))
          temp.push({
            latitude: coors[i],
            longitude: coors[i + 1],
          })
        }
        this.routePathObj[i] = temp

        if (Object.getOwnPropertyNames(this.routePathObj).length === this.data.path.length) {
          for (let k in this.routePathObj) {
            this.routePath[k] = this.routePathObj[k]
          }
          this.routePath = this.routePath.flat()
          this.$emit('refreshMapPreviewData', { distance: this.distance, routePath: this.routePath })
        }
        this.drawPolyline(pl)
      } else {
        this.$swal.warning(res.message)
      }
    }.bind(this)
  },
  mounted () {
    if (window.qq) {
      window.initMapPreview()
    } else {
      this.loadScript('https://map.qq.com/api/js?v=2.exp&key=' + key + '&callback=initMapPreview')
      //this.loadScript('https://map.qq.com/api/gljs?v=1.exp&key=' + key + '&callback=initMapPreview')
    }
  },
  methods: {
    renderMarker () {
      for (let v of this.marker) {
        v.setMap(null)
      }
      this.marker.length = 0

      //marker的容器大小 px
      setTimeout(() => {
        for (let item of this.data.spot) {
          const location = new qq.maps.LatLng(item.latitude, item.longitude)
          const mt = this.$refs[`tourMarker${item.spotId}`][0].$el
          const decoration = new qq.maps.MarkerDecoration(mt, new qq.maps.Point(0, 0))
          let marker = new qq.maps.Marker({
            position: location,
            map: this.map,
            autoRotation: true,
            decoration,
          })
          // 用透明图片设置marker的容器大小
          let icon = new qq.maps.MarkerImage(
            require(`./marker-decoration.png`),
            new qq.maps.Size(22, 22),
            new qq.maps.Point(0, 0),
            new qq.maps.Point(11, 11),
          )
          marker.setIcon(icon)
          this.marker.push(marker)

          // 修改marker容器的overflow限制
          setTimeout(() => {
            mt.parentElement.parentElement.style.overflow = 'visible'
          }, 100)
        }
      }, 300)
    },
    renderPath () {
      this.distance = 0
      this.routePath.length = 0
      this.routePathObj = {}
      for (let v of this.polyline) {
        v.setMap(null)
      }
      this.polyline.length = 0

      if (this.data.path && this.data.path.length > 0) {
        //生成

        for (let i = 0; i < this.data.path.length - 1; i++) {
          /*          this.loadScript("https://apis.map.qq.com/ws/direction/v1/walking/?" +
                      qs.stringify({
                        from: this.data.path[i].latitude + ',' + this.data.path[i].longitude,
                        to: this.data.path[i + 1].latitude + ',' + this.data.path[i + 1].longitude,
                        output: 'jsonp',
                        callback: 'cb',
                        key
                      }))*/
          /*          axios.request({
                      method: 'get',
                      url: "https://apis.map.qq.com/ws/direction/v1/walking",
                      params: {
                        from: this.data.path[i].latitude + ',' + this.data.path[i].longitude,
                        to: this.data.path[i + 1].latitude + ',' + this.data.path[i + 1].longitude,
                        output: 'jsonp',
                        key
                      },
                      header: {"content-type": "application/json"},
                      withCredentials: true
                    }).then(res => {
                      debugger
                    })*/
          jsonp('https://apis.map.qq.com/ws/direction/v1/walking', {
            from: this.data.path[i].latitude + ',' + this.data.path[i].longitude,
            to: this.data.path[i + 1].latitude + ',' + this.data.path[i + 1].longitude,
            output: 'jsonp',
            key
          }).then(res => {
            cb(res, i)
          })
        }
      } else if (this.data.routePath) {
        //回显
        let pl = []
        for (let i = 0; i < this.data.routePath.length; i++) {
          pl.push(new qq.maps.LatLng(this.data.routePath[i].latitude, this.data.routePath[i].longitude))
        }
        this.drawPolyline(pl)
      }
    },
    renderImg () {
      this.groundOverlay && this.groundOverlay.setMap(null)

      if (this.data.location?.length === 3 && this.data.mapPath) {
        this.groundOverlay = new qq.maps.GroundOverlay
        //设置显示图片的地图上的矩形区域
        this.groundOverlay.setBounds(
          new qq.maps.LatLngBounds(new qq.maps.LatLng(this.data.location[1].latitude, this.data.location[1].longitude),
            new qq.maps.LatLng(this.data.location[2].latitude, this.data.location[2].longitude)))
        //设置覆盖层可见，默认为true
        this.groundOverlay.setVisible(true)
        this.groundOverlay.setOptions({
          //设置显示地面覆盖层的地图
          map: this.map,
          //设置图片地址
          imageUrl: this.data.mapPath,
          //设置覆盖层的透明度
          opacity: 1,
          //设置地面覆盖层可响应鼠标事件，默认为true
          clickable: true,
          zIndex: 1,
        })

        this.map.setCenter(new qq.maps.LatLng(this.data.location[0].latitude, this.data.location[0].longitude))
      }
    },
    drawPolyline (path) {
      this.polyline.push(new qq.maps.Polyline({
        path,
        strokeColor: '#00ba6a',
        strokeWeight: 6,
        editable: false,
        map: this.map,
        zIndex: 99,
      }))
    },
    loadScript (src) {
      let script = document.createElement('script')
      script.type = 'text/javascript'
      script.src = src
      document.body.appendChild(script)
    },
  }
}
</script>

<style lang="scss" scoped>
#map-direction {
  height: 969px;
  position: relative;
  margin-top: 1rem;
}
</style>
